package com.tzy.gateway.config;
import com.tzy.common.constant.CacheConstant;
import com.tzy.gateway.service.RedisService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
/**
 * 自定义全局过滤器
 */
@Data
@Slf4j
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisService redisService;
    @Value("#{'${filter.exclude}'.split(',')}")
    private List excludeList;
    /**
     * 不拦截登录和注册的请求
     * 该 GlobalFilter会校验请求中是否包含了“token”，如何不包含请求参数“token”则不转发路由，否则执行正常的逻辑。
     *
     * @param exchange 包含request和response对象
     * @param chain    过滤器链
     * @return Mono<Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        String path = request.getPath().value();//获取请求上下文
        log.info("contextPath=" + path);
        log.info("list=" + excludeList);
        if (excludeList.contains(path)) {
            log.info("过滤器执行放行操作");
            return chain.filter(exchange);
        }
//                     "    \"data\": false \n"+
        String webResult = "\n{\n" +
                "  \"code\": 2,\n" +
                "  \"msg\": \"用户没有登录\",\n" +
                "  \"result\": {\n" +
                "    \"data\": \"The user is not logged in\"\n" +
                "  }\n" +
                "}";
        log.info("webResult="+webResult);
        String userId = request.getHeaders().getFirst(CacheConstant.HEADER_USER_ID);
        log.info("userId=" + userId);
        if (!(StringUtils.isBlank(userId))) {//当 uid不为空
            String token = request.getHeaders().getFirst(CacheConstant.HEADER_TOKEN);
            log.info("HEADER_TOKEN="+token);
            //token为空说明未登录， 拦截
            if (StringUtils.isBlank(token)) {
                log.info("token为空过滤拦截");
                DataBuffer data = dataBufferFactory.wrap(webResult.getBytes());
                return response.writeWith(Mono.just(data));
            }
            log.info("token不为空=" + token);
            //token不为空
            //从 redis里取 token,并比较是否一致,是就返回 true
            String cacheToken = redisService.getString(CacheConstant.TOKEN_PREFIX + userId);
            log.info("cacheToken="+cacheToken);
            if(null != cacheToken){
                log.info("cacheToken=" + cacheToken);
                if ((token.equals(cacheToken))) {//token一致
                    log.info("过滤器放行");
                    return chain.filter(exchange);
                }
            }
            log.info("cacheToken为空 webResult="+webResult);
            DataBuffer data = dataBufferFactory.wrap(webResult.getBytes());
            return response.writeWith(Mono.just(data));
        }
        log.info("finally: userId为空");
        DataBuffer data = dataBufferFactory.wrap(webResult.getBytes());
        return response.writeWith(Mono.just(data));
    }
    //    @Override//田港的网关过滤器
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        String path = exchange.getRequest().getPath().value();
//        if(excludeList.contains(path)){
//            return chain.filter(exchange);
//        }
//        String uid = exchange.getRequest().getHeaders().getFirst(CacheConstant.HEADER_USER_ID);
//        if(StringUtils.isBlank(uid)){
//            String token = exchange.getRequest().getHeaders().getFirst(CacheConstant.HEADER_TOKEN);
//            if(StringUtils.isBlank(token)){
//                String cacheToken = redisService.getString(CacheConstant.TOKEN_PREFIX+uid);
//                if(token.equals(cacheToken)){
//                    return chain.filter(exchange);
//                }
//            }
//        }
//        ServerHttpResponse response = exchange.getResponse();
//        DataBufferFactory dataBufferFactory = response.bufferFactory();
//        DataBuffer data = dataBufferFactory.wrap("no login".getBytes());
//        return response.writeWith(Mono.just(data));
//    }
    public Mono<Void> filterDemo(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uid = exchange.getRequest().getHeaders().getFirst("uid");
        if (StringUtils.isBlank(uid)) {
            String token = exchange.getRequest().getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)) {
                if ("1".equals(uid) && "token".equals(token)) {
                    return chain.filter(exchange);
                }
            }
        }
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer data = dataBufferFactory.wrap("no login".getBytes());
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
